var utils = require('./utils');
var cheerio = require('cheerio');
var dao = require('./dao');


exports.loadComment = loadComment;

function loadComment(sku,page,time,ep) {

    var url = "https://club.jd.com/comment/skuProductPageComments.action?productId="+sku+"&score=0&sortType=6&page={PAGE}&pageSize=10&isShadowSku=0";
    url = url.replace("{PAGE}",page);
    utils.getc(url,1,function (data) {
        //console.log(data);
        var flag = true,json,comm = [];
        var params = [];
        var sql = "replace into t_jd_hot_key_comment(fetch_time,id,sku_id,comment_page_num,comment_page_set,";
        sql += "creation_time,is_top,pro_color,pro_size,pro_name,reference_time,score,";
        sql += "user_province,nick_name,user_client,isMobile,days,content,vip_lv,vip_lv_name,img_url)";
        sql += "values(CURDATE(),?,?,?,?, ?,?,?,?,?,?,?, ?,?,?,?,?, ?,?,?,? );";

        try {
            json = JSON.parse(data);
            comm = json.comments;

            for(var i in comm){
                var obj = comm[i];
                obj.pageNum = page+1;
                obj.index = i;
                var imgs = obj.images;
                var img_url = "";
                for(var i in imgs){
                    img_url += imgs[i].imgUrl+";";
                }
                //console.log(obj.creationTime+":"+obj.content);
                var d = new Date(obj.creationTime);
                var d1 = new Date(time);
                flag = d > d1;
                //dao.saveComment(obj);
                params.push([obj.id,obj.referenceId, obj.pageNum,obj.index,obj.creationTime,obj.isTop,obj.productColor,obj.productSize,
                    obj.referenceName,obj.referenceTime,obj.score, obj.userProvince,obj.nickname,obj.userClientShow,
                    obj.isMobile,obj.days,obj.content,obj.userLevelId,obj.userLevelName,img_url]);
            }

           
            if(comm.length){
                dao.execTrans(sql,params,function (err) {
                    if(err) console.log(err + "");
                    if(comm.length>0&&flag){
                        ep.emit("next_page",sku);
                    }else{
                        ep.emit("next_word",sku);
                    }
                });
            }else{
                console.log(data);
                ep.emit("next_word",sku);
            }
           

        } catch (e){
            console.log(data);
            console.log(e);
            ep.emit("next_word",sku);
        }



    })

}
/*
test();
function test() {
    var d = new Date('2017-02-03 00:12:12');
    var d1 = new Date('2017-01-01 00:12:12');
    console.log(d>d1);
}*/
